package images

import (
	"context"
	"fmt"

	"server/internal/common/biz"
	"server/internal/svc"
	"server/internal/types"
	"server/internal/utils"

	"github.com/docker/docker/api/types/image"
	"github.com/zeromicro/go-zero/core/logx"
)

type ImagesLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewImagesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ImagesLogic {
	return &ImagesLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ImagesLogic) Images(req *types.ImagesReq) (resp []types.ImagesResp, err error) {
	images, err := l.svcCtx.DockerCli.ImageList(l.ctx, image.ListOptions{})
	if err != nil {
		l.Logger.Errorf("ImageList error: %v", err)
		return nil, biz.ImageGetError
	}

	resp = make([]types.ImagesResp, 0, len(images))
	for index, image := range images {
		l.Logger.Debug(utils.PrintLog(fmt.Sprintf("imageList[%d]", index), image))
		resp = append(resp, *toResp(&image))
	}
	return
}

/*
	{
	  "Containers": -1,
	  "Created": 1683046167,
	  "Id": "sha256:d2c94e258dcb3c5ac2798d32e1249e42ef01cba4841c2234249495f87264ac5a",
	  "Labels": null,
	  "ParentId": "",
	  "RepoDigests": [
	    "hello-world@sha256:d211f485f2dd1dee407a80973c8f129f00d54604d2c90732e8e320e5038a0348"
	  ],
	  "RepoTags": [
	    "hello-world:latest"
	  ],
	  "SharedSize": -1,
	  "Size": 13256
	}
*/
func toResp(image *image.Summary) *types.ImagesResp {
	return &types.ImagesResp{
		RepoTags: image.RepoTags,
		Id:       image.ID[7:20],
		Created:  utils.FormatTimestamp(image.Created),
		Size:     image.Size,
	}
}
